package com.javastudy.liuhouse.xml_json;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;

public class XmlParse {

    @Test
    public  void mains() throws ParserConfigurationException, IOException, SAXException {
        //从根目录中加载xml文件并且进行解析 【demo.xml是再根目录下面的 ， src就是根目录】
        InputStream input = getClass().getClassLoader().getResourceAsStream("demo.xml");
        //解析并获取Document对象 [可以看出来 DocumentBuilderFactory 其实是java的内置对象]
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        //使用文档构造器  解析 xml文件资源
        Document doc = db.parse(input);
        //打印文档
        printNode(doc , 0);
    }


    static void printNode(Node n , int indent){
        for(int i = 0 ; i < indent; i++){
            System.out.println(" ");
        }
        switch (n.getNodeType()){
            case Node.DOCUMENT_NODE:
                System.out.println("Document:" + n.getNodeName());
                break;
            case Node.ELEMENT_NODE:
                System.out.println("Element:" + n.getNodeName());
                break;
            case Node.TEXT_NODE:
                System.out.println("Text:" + n.getNodeName() + "=" + n.getNodeValue());
                break;
            case Node.ATTRIBUTE_NODE:
                System.out.println("Attr:" + n.getNodeName() + "="+ n.getNodeValue());
                break;
            case Node.CDATA_SECTION_NODE:
                System.out.println("CDATA:" + n.getNodeName() + "=" + n.getNodeValue());
                break;
            case Node.COMMENT_NODE:
                System.out.println("Comment:" + n.getNodeName() + "=" + n.getNodeValue());
                break;
            default:
                System.out.println("NodeType:" + n.getNodeType() + ",NodeName:" + n.getNodeName());
        }
        //for循环还可以这样使用  只要是能产生迭代的就可以
        for(Node child = n.getFirstChild(); child != null ; child = child.getNextSibling()){
            printNode(child , indent + 1);
        }


    }


}
